const tagInfo = "/utils/net/Http";
import to from "await-to-js";
import request from "../request";
import { Session } from "/@/utils/storage";
const Http = {
	async post(url: string, param: object = {}, headers: object = {}): Promise<any> {
		let combineData = this.combineData(param, headers);
		let [err, res] = await to(request.post(url, combineData.param, { headers: combineData.headers }));
		if (err) {
			return { code: 999, data: err, msg: "请求失败" };
		}
		return res;
	},
	async get(url: string, param: object = {}, headers: object = {}): Promise<any> {
		let combineData = this.combineData(param, headers);
		let [err, res] = await to(request.get(url, { params: combineData.param, headers: combineData.headers }));
		if (err) {
			console.log("err", err);
			return { code: 999, data: err, msg: "请求失败" };
		}
		return res;
	},
	combineData(param: any = {}, headers: any = {}): any {
		// 在请求发送之前做一些处理
		// 让每个请求携带token-- ['X-Token']为自定义key 请根据实际情况自行修改
		// config.headers['X-Token'] = token;
		let token = Session.get("token");
		if (token) {
			headers["Authorization"] = token;
			headers["Accept"] = "*/*";
			// param["token"] = token;
		}
		// console.log(tagInfo, "http:param", param);
		// console.log(tagInfo, "http:headers", headers);
		return { param, headers };
	},
	/**上传文件/图片
	 * @param url 上传地址
	 * @param tempFiles 临时文件
	 * @param is_multipart 是否多文件上传(默认为0 -> 0单文件 | 1多文件)
	 * @returns Promise
	 */
	async upload(url: string, tempFiles: any, is_multipart: number = 0): Promise<any> {
		let token = Session.get("token");
		// 构建FormData对象,通过该对象存储要上传的文件
		let formData = new FormData();
		// 遍历当前临时文件List,将上传文件添加到FormData对象中
		for (let item of tempFiles) {
			formData.append(is_multipart == 0 ? "file" : "file[]", item);
		}
		let options = {
			headers: {
				// 表示上传的是文件,而不是普通的表单数据
				"Content-Type": "multipart/form-data",
				Authorization: token,
				Accept: "*/*"
			}
		};
		let [err, res] = await to(request.post(url, formData, options));
		if (err) {
			console.log("err", err);
			return { code: 999, data: err, msg: "上传失败" };
		}
		return res;
	}
};

export default Http;
